import json
import traceback

from django.http.response import JsonResponse
from django.utils.deprecation import MiddlewareMixin
from django.contrib.auth.models import AnonymousUser
from django.conf import settings

from wass.settings import BACKUP_RESTORE_KEY, BACKUP_DUMP_KEY
from apps.system_manage.script import unique_operation
from apps.account_manager.account_utils import get_header_token, check_token_expire
from utilities.djconsole import djconsole
from utilities.utils import CustomJSONEncoder


class LicenseInfoMiddleware(MiddlewareMixin):
    def process_request(self, request):
        url_path = request.path
        if url_path not in ["/api/v1/system/license/", "/api/v1/system/license"]:
            try:
                res = djconsole.get_license_detail(request)
                if (not res.get("uuid")) and url_path:
                    data = {"status": "fail", "errcode": "40000401", "data": "License not exists."}
                    return JsonResponse(data=data, status=401)
            except Exception:
                traceback.print_exc()
                data = {"status": "fail", "errcode": "40000401", "data": "Djconsole error or license not exists."}
                return JsonResponse(data=data, status=401)


class RequestFormatMiddleware(MiddlewareMixin):

    def process_request(self, request, *args, **kwargs):
        whitelist = ["/api/v1/system/backup-recovery/progress/", "/api/v1/account/refresh/"]
        if request.path not in whitelist and request.method != 'GET':
            message = None
            if djconsole.check_is_bk():
                message = '系统正在进行数据备份或者恢复，无法进行此操作'
            if message:
                return JsonResponse(data={
                    "status": 'failed',
                    'message': message,
                    'errcode': "40301403"
                }, status=403)


class ResponseFormatMiddleware(MiddlewareMixin):

    def process_response(self, request, response):
        response = self.format_data(request, response)
        response = self.network(response)
        return response

    def format_data(self, request, response):
        if hasattr(response, "data") and (
            isinstance(response.data, dict) or isinstance(response.data, list)
        ):
            data = response.data
            status_code = response.status_code
            if (
                ("errcode" not in data)
                and ("status" not in data)
                and 200 <= status_code <= 300
            ):
                response.data = {"status": "success", "errcode": 0, "data": data}
            elif (
                ("errcode" not in data)
                and ("status" not in data)
                and 400 <= status_code
            ):
                response.data = {"status": "fail", "errcode": -1, "data": data}
            response.data.update(
                {
                    # "mode": get_system_mode(),
                }
            )
            response.data.setdefault("user_group", self.user_group(request))
            response.data.setdefault("errcode", 0)
            response.content = json.dumps(response.data, cls=CustomJSONEncoder)
        return response

    def user_group(self, request):
        user = request.user
        if isinstance(user, AnonymousUser):
            user_group = []
        else:
            user_group = [g.group for g in user.group]
        return user_group

    def network(self, response):
        """
        检查透明直连模式网络配置
        """
        # response["mode_network"] = check_network_config()
        return response


class RequestTokenMiddleware(MiddlewareMixin):

    def process_request(self, request, *args, **kwargs):
        token = get_header_token(request, only_token=True)
        if not token:
            return None
        # 判断一下token 长度， 过滤一下 "null", "undefined"
        if not settings.DEBUG and len(token) > 20 and not check_token_expire(token):
            data = {"status": "fail", "errcode": "40001401", "data": "token expired."}
            return JsonResponse(data=data, status=401)
